
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.sini.com.spire.doc.Document;
// import com.spire.doc.FileFormat;
import com.sini.com.spire.doc.FileFormat;

import Entity.DANXUAN_Entity;


public class OneF {
    
    @Override
    public String toString() {
        return "[ Word文档=" + docx_file + ", Excel文件=" + excel_book.book_file+ ", 生成=" + (isYouxiao?"成功":"失败") + " ]";
    }

    // 对应的docx_file文档
    public File docx_file;

    // 对应的txt文档
    public Path txt_file_path;
    public File txt_file;

    // 对应docx文档文件名
    public String docx_filename;
    // docx文档目录路径
    public Path docx_directory;
    // 对应的excel对象
    public BookF excel_book;

    // 判断是否能正确生成Excel
    public boolean isYouxiao=true;

    public void get_txt(File docx_file,File txt_file) throws IOException{
        FileInputStream inputStream;
        Document document;
        try {
            inputStream = new FileInputStream(docx_file);
            document= new Document();
            document.loadFromStream(inputStream, FileFormat.Docx);
            
        //将结果文档保存到流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        // document.savetost
        // document.saveToStream(bos, FileFormat.Txt);
        // document.saveToTxt("~$Output1.txt", StandardCharsets.UTF_8);

        // 只需要把这个弄成input流就可以了
        // document.
        //将流写入WPS文档
        FileOutputStream fos = new FileOutputStream(txt_file);
        // fos.write(bos.toByteArray());
        // FileInputStream fis = new FileInputStream();
        // fis.rea
            
            // ByteArrayOutputStream bos = new ByteArrayOutputStream();
            document.saveToTxt(txt_file.toString(), StandardCharsets.UTF_8);
            fos.close();
            bos.close();
            document.close();
            inputStream.close();

        } catch (Exception e) {
            //TODO: handle exception
            throw e;
        }


        // bos.close();        
    }

    public OneF build(){
        
        this.docx_filename=this.docx_file.getName().split("\\.")[0];
        this.docx_directory=Path.of(this.docx_file.getPath()).getParent();
        Path excel_file_path=Paths.get(this.docx_directory.toString(), this.docx_filename+".xls");

        this.txt_file_path=Paths.get(this.docx_directory.toString(), "~"+this.docx_filename+".txt");
        // this.txt_file_path=Paths.get(this.docx_directory.toString(), "~"+this.docx_filename+".txt");

        this.txt_file=this.txt_file_path.toFile();


        this.excel_book=new BookF(excel_file_path.toFile());
        //生成txt文档
        try {
            this.get_txt(this.docx_file, this.txt_file);

            // 设置txt文件显示属性
            BasicFileAttributes attrs = Files.readAttributes(this.txt_file_path, BasicFileAttributes.class);
            // 设置文件为隐藏
            Files.setAttribute(this.txt_file_path, "dos:hidden", true);

        } catch (IOException e) {
            this.isYouxiao=false;
            e.printStackTrace();
        }
        if(this.isYouxiao){ //有效才继续转换
            // this.trans_docx();
            //调用FromList中的转换word到Excel方法
            FromList.docx_to_excel(this.excel_book, this);
            // 对Excel表内容进行查看，判断是否转换失败
            // this.isYouxiao=Check(this.excel_book);
        }
        // this.excel_book.
        return this;
    }

    private boolean Check(BookF excel_book2) {
        Collection<SheetF> list=excel_book2.sheet_HashMap.values();
        // 判断是否生成的四个表都为空
        for (SheetF sheetF : list) {
            if(!sheetF.getData().isEmpty()){
                return true;
            }
        }
        return false;
    }

    public OneF(File docx_file) {
        this.docx_file = docx_file;
    }

    // 一些特别的正则表达式
    public static String duoxuan_regx="^[A-Z]\\.";
    public static Pattern duoxuan_pattern=Pattern.compile(duoxuan_regx);

    public static String ti_regx="^\\d+\\.";
    public static Pattern ti_pattern=Pattern.compile(ti_regx);

    // public static String zheng_regx="（正确）$";
    public static String zheng1_regx="（正确）。?$";
    // public static String cuo_regx="（错误）$";
    public static String cuo1_regx="（错误）。?$";

    // public static Pattern zheng_pattern=Pattern.compile(zheng_regx);
    public static Pattern zheng1_pattern=Pattern.compile(zheng1_regx);
    // public static Pattern cuo_pattern=Pattern.compile(cuo_regx);
    public static Pattern cuo1_pattern=Pattern.compile(cuo1_regx);

    private void get_excel(){
        
    }


    // private void trans_docx(){
    //     // 创建单选，多选，判断，问答，四个表
    //     SheetF<DANXUAN_Entity> danxuan_sheet = new SheetF<>("单选", DANXUAN_Entity.class, this.excel_book);
    //     SheetF<DUOXUAN_Entity> duoxuan_sheet = new SheetF<>("多选", DUOXUAN_Entity.class, this.excel_book);
    //     SheetF<PANDUAN_Entity> panduan_sheet = new SheetF<>("判断", PANDUAN_Entity.class, this.excel_book);
    //     SheetF<WENDA_Entity> wenda_sheet = new SheetF<>("问答", WENDA_Entity.class, this.excel_book);

    //     try (FileInputStream fis = new FileInputStream(this.docx_file)) {
    //         XWPFDocument document = new XWPFDocument(fis);
    //         // 获取所有段落
    //         List<XWPFParagraph> paragraphs = document.getParagraphs();

    //         // 剔除空段
    //         Stream<XWPFParagraph> stream = paragraphs.stream();
    //         Stream<XWPFParagraph> filter = stream.filter(s -> !s.getParagraphText().isEmpty());

    //         List<XWPFParagraph> collect = filter.collect(Collectors.toList());
    //         List<String> all_lines = new ArrayList<>();
    //         // 将所有段落转化成List<String>类型，并且对于不合理的段落进行处理，直到每个题都是空段结尾
    //         for (XWPFParagraph paragraph : collect) {
    //             String line = paragraph.getParagraphText().trim();
    //             if (line.contains("   ")) {
    //                 String[] new1 = line.split("   ");
    //                 for (String string : new1) {
    //                     if(!string.isEmpty()){
    //                         all_lines.add(string);
    //                     }
    //                 }
    //             } else {
    //                 all_lines.add(line);
    //             }
    //         }

    //         // 最终得到word文档里的所有段落
    //         // all_lines：List<String>
    //         // 开始对word文档进行处理
    //         Choose_Type type = Choose_Type.Other;
    //         int[] idx={0};
    //         do {
    //             String line = all_lines.get(idx[0]);
    //             switch (line) {
    //                 case "一、单选题":
    //                     type = Choose_Type.DANXUAN;
    //                     idx[0]++;
    //                     break;
    //                 case "二、多选题":
    //                     type = Choose_Type.DUOXUAN;
    //                     idx[0]++;
    //                     break;
    //                 case "三、判断题":
    //                     type = Choose_Type.PANDUAN;
    //                     idx[0]++;
    //                     break;
    //                 default:
    //                     // i--;
    //                     // type = Type.Other;
    //                     break;
    //             }
    //             line = all_lines.get(idx[0]);
    //             if(is_matcher_finder(line,ti_pattern)){
    //                 Deal_DANXUAN(type,danxuan_sheet,all_lines,idx);
    //                 // Deal_DUOXUAN(type,duoxuan_sheet,all_lines,idx);
    //                 // Deal_PANDUAN(type,panduan_sheet,all_lines,idx);
    //             }else{
    //                 idx[0]++;
    //             }

    //         } while (idx[0]< all_lines.size());

    //         // 关闭文档
    //         document.close();

    //     } catch (IOException e) {
    //         e.printStackTrace();
    //     }
    //     excel_book.add_sheet(danxuan_sheet);
    //     // excel_book.add_sheet(duoxuan_sheet);
    //     // excel_book.add_sheet(panduan_sheet);
    //     // excel_book.add_sheet(wenda_sheet);
    //     // excel_book.writer();
    // }

    public void write_to_excel() {
        this.excel_book.writer();
    }
    

    private  boolean is_matcher_finder(String line, Pattern ti_pattern2) {
        Matcher matcher=ti_pattern2.matcher(line);
        // System.out.println(matcher.find());
        return matcher.find();
    }

    // private  void Deal_PANDUAN(Choose_Type type, SheetF<PANDUAN_Entity> panduan_sheet, List<String> all_lines,
    //         int[] idx) {
    //             int i=0;
    //             if (type == Choose_Type.PANDUAN) {
    //                 PANDUAN_Entity data = new PANDUAN_Entity();
                    
    //                 fill_value(data,i++,1,panduan_sheet.getBook_father().book_name);
    //                 // data.setStr1(danxuan_sheet.getBook_father().book_name);
        
    //                 String[] str = all_lines.get(idx[0]++).split(" ");

    //                 if(is_matcher_finder(str[1], zheng1_pattern)){
    //                     String result=str[1].replaceAll(zheng1_regx, "");
    //                     fill_value(data, i, 3, "正确");
    //                     fill_value(data, i, 2, result);
    //                 }
    //                 if(is_matcher_finder(str[1], cuo1_pattern)){
    //                     String result=str[1].replaceAll(cuo1_regx, "");
    //                     fill_value(data, i, 3, "错误");
    //                     fill_value(data, i, 2, result);
    //                 }

    //                 if(idx[0]>=all_lines.size()){
    //                     panduan_sheet.getData().add(data);
    //                     return;
    //                 }

    //                 str[1] = all_lines.get(idx[0]++);
    //                 if(is_matcher_finder(str[1], ti_pattern)){
    //                     idx[0]--;
    //                 }else{
    //                     fill_value(data,i++,4,str[1].substring(0 + 3, str[1].length()).trim());
    //                 }
    //                 // data.setStr4(str[1].substring(0 + 3, str[1].length()));

    //                 panduan_sheet.getData().add(data);
    //             }
    // }

    // private  void Deal_DUOXUAN(Choose_Type type, SheetF<DUOXUAN_Entity> duoxuan_sheet, List<String> all_lines,
    //         int[] idx) {
    //             int i=1;
    //     if (type == Choose_Type.DUOXUAN) {
    //         DUOXUAN_Entity data = new DUOXUAN_Entity();
            
    //         fill_value(data,i++,1,duoxuan_sheet.getBook_father().book_name);
    //         // data.setStr1(danxuan_sheet.getBook_father().book_name);

    //         // 题目
    //         String[] str = all_lines.get(idx[0]++).split(ti_regx+" ");
    //         fill_value(data,i++,2,str[1]);
    //         // System.out.println(str[1]);
    //         // data.setStr2(str[1]);
    //         // System.out.println(str[0]);

    //         // 这里需要对多个行内容进行判断

    //         String one=all_lines.get(idx[0]++);
    //         Matcher matcher=duoxuan_pattern.matcher(one);
    //         int sheet_idx=5;
    //         // System.out.println(matcher.find());
    //         while(matcher.find()){
    //             // System.out.println(one);              
    //             fill_value(data, i, sheet_idx++, one.split(" ")[1]);
    //             one=all_lines.get(idx[0]++);
    //             matcher=duoxuan_pattern.matcher(one);
    //         }

           
    //         str[1] = all_lines.get(idx[0]-1);
    //         // data.setStr4(str[1].substring(0 + 3, str[1].length()));
    //         fill_value(data,i++,3,str[1].substring(0 + 3, str[1].length()));
    //         // idx[0]++;

    //         str[1] = all_lines.get(idx[0]++);
    //         // data.setStr4(str[1].substring(0 + 3, str[1].length()));
    //         fill_value(data,i++,4,str[1].substring(0 + 3, str[1].length()));

    //         duoxuan_sheet.getData().add(data);
    //     }
    // }

    private void Deal_DANXUAN(Choose_Type type, SheetF danxuan_sheet, List<String> all_lines, int[] idx) {
        int i=1;
        if (type == Choose_Type.DANXUAN) {
            DANXUAN_Entity data = new DANXUAN_Entity();
            
            fill_value(data,i++,1,danxuan_sheet.getBook_father().book_name);
            // data.setStr1(danxuan_sheet.getBook_father().book_name);

            String[] str = all_lines.get(idx[0]++).split(" ");
            fill_value(data,i++,2,str[1]);
            // data.setStr2(str[1]);
            // System.out.println(str[0]);

            str = all_lines.get(idx[0]++).split(" ");
            fill_value(data,i++,5,str[1]);

            // data.setStr5(str[1]);

            str = all_lines.get(idx[0]++).split(" ");
            fill_value(data,i++,6,str[1]);

            // data.setStr6(str[1]);

            str = all_lines.get(idx[0]++).split(" ");
            // data.setStr7(str[1]);
            fill_value(data,i++,7,str[1]);


            str = all_lines.get(idx[0]++).split(" ");
            // data.setStr8(str[1]);
            fill_value(data,i++,8,str[1]);


            str[1] = all_lines.get(idx[0]++);
            // data.setStr3(str[1].substring(0 + 3, str[1].length()));
            fill_value(data,i++,3,str[1].substring(0 + 3, str[1].length()));


            str[1] = all_lines.get(idx[0]++);
            // data.setStr4(str[1].substring(0 + 3, str[1].length()));
            fill_value(data,i++,4,str[1].substring(0 + 3, str[1].length()));

            danxuan_sheet.getData().add(data);
        }
    }

    private  void fill_value(DANXUAN_Entity data, int i, int entity_idx, String value) {
        switch (entity_idx) {
            case 1:
                data.setStr1(value);
                break;
            case 2:
                data.setStr2(value);
                break;
                case 3:
                data.setStr3(value);
                break;
           
           case 4:
                data.setStr4(value);
                break;
           
           case 5:
                data.setStr5(value);
                break;
           
           case 6:
                data.setStr6(value);
                break;
           
           case 7:
                data.setStr7(value);
                break;
           
           case 8:
                data.setStr8(value);
                break;
           
           case 9:
                data.setStr9(value);
                break;
           
           case 10:
                data.setStr10(value);
                break;
            default:
                break;
        }
    }

    public void deal_txt() {
        try {
            Files.delete(this.txt_file_path);
            System.out.println("文件删除成功");
        } catch (IOException e) {
            System.out.println("文件删除失败");
            e.printStackTrace();
        }
    }

    
}
